<script setup lang="ts">
// -- imports
import { ref } from 'vue';
import { api,apiCommon } from '@/api/apiServer';
import AppHeader from '@/components/@lgs/AppHeader/AppHeader.vue';
import Tools from '@likg/tools';
import vipbg from "@/assets/images/vip-bg.png";
import kamibg from "@/assets/images/kami-bg.png";

import touxiang from '@/assets/images/default.png';
import editico from '@/assets/images/edit.png';
import { showToast } from 'vant';
// -- constants
const env = ref(Tools.getEnv());

const dialogShow = ref(false);
const cardPwd = ref('');
const countdown = ref(60); // 倒计时时间
// 从localStorage获取剩余时间
const savedTime = localStorage.getItem('countdownTime');

let timer:any = null;

// 获取用户信息
const userInfo = ref<any>({});
const getUserInfoFn = async () => {
  let res = await api.getUserInfo();
  if(res.code === 200) {
    userInfo.value = res.data;
  }
}
getUserInfoFn();

// 获取卡密输错次数
let cardErrorNumStr = sessionStorage.getItem("cardErrorNum");
const cardErrorNum = ref( cardErrorNumStr?parseInt(cardErrorNumStr, 10) : 0);

// 卡密激活
const jihuoFn = async () => {
  if(!cardPwd.value) {
    showToast({
      message: '请输入卡密'
    })
    return
  }
  api.activeCard({
    cardPassword:cardPwd.value
  }).then(res => {
    if(res.code === 200) {
    dialogShow.value = false;
    if(timer) {
      clearInterval(timer);
    }
    cardErrorNum.value = 0;
    sessionStorage.removeItem("cardErrorNum");
    showToast({
      message: '卡密激活成功'
    })
  }
  }).catch(err => {
    cardErrorNum.value = Number(cardErrorNum.value) + 1;
    sessionStorage.setItem("cardErrorNum",cardErrorNum.value.toString());

    if(cardErrorNum.value >= 5) {
      if (countdown.value === 60) {
          startCountdown();
      }
    }
  })

}

const startCountdown = () => {
  timer = setInterval(() => {
      countdown.value--;
      localStorage.setItem('countdownTime', countdown.value.toString()); // 保存剩余时间
      if (countdown.value <= 0) {
          clearInterval(timer);
          countdown.value = 60;
          cardErrorNum.value = 0;
          sessionStorage.removeItem("cardErrorNum");
          localStorage.removeItem('countdownTime'); // 清除localStorage中的时间
      }
  }, 1000);
}

if (savedTime) {
   countdown.value = parseInt(savedTime, 10);
   startCountdown();
}

// 替换手机号
const replatePhoneFn = (str:string) => {
   // 把下面的手机号第4位到第7位换成****
    var reg = /^(\d{3})\d*(\d{4})$/;
    var replaceStr = '$1****$2';
    if(str) {
      var newStr = str.replace(reg, replaceStr);
      return newStr
    } else {
      return ''
    }
}

const afterRead = async (file:any) => {
      const formData = new FormData();
      formData.append("file", file.file);

      let res:any = await apiCommon.upload(formData);
      if(res.code === 200) {
        userInfo.value.userHeadImage = res.data.thUrl;
        changeHead()
      } else {
        showToast({
            message: res.msg,
            icon: 'none'
        })
      }
    }

    // 修改头像
    const changeHead = async () => {
       await api.uploadUserHeadImage({
        userHeadImage:userInfo.value.userHeadImage
      })
    }
</script>

<template>
  <div class="page ">
    <app-header v-if="env !== 'weixin'" title="我的" gradientColor="transparent" :show-status-bar="false" />
    <div class="flex-h-start px-10 pt-50">
        <van-image
          round
          width="55px"
          height="55px"
           :src="userInfo.userHeadImage || touxiang"
        />
        <div class="f16 ml-10">{{replatePhoneFn(userInfo.phoneNumber)}}</div>
        <van-uploader :after-read="afterRead">
          <van-icon :name="editico"  size="20" color="#B4B4B4" class="ml-10" style="top:-5px;"/>
        </van-uploader>
      </div>
<!--      <div class="px-10 mt-23">-->
<!--        <van-image width="100%" :src="vipbg"  @click="$router.push('/login/bindCar?customerId='+userInfo.customerId)"/>-->
<!--      </div>-->
<!--      <div class="px-10 mt-5 position-relative">-->
<!--        <img src="@/assets/images/car-ico.png" class="position-absolute" style="width:60px; top:50%; left:25px;z-index:99; transform: translateY(-50%);"/>-->
<!--        <van-image width="100%" :src="kamibg"  @click="dialogShow = true"/>-->
<!--      </div>-->


      <van-dialog v-model:show="dialogShow" title="请输入您的卡密" :showConfirmButton="false">
            <div class="flex-v-center mt-10">
              <van-field v-model="cardPwd"  type="text" clearable placeholder="请输入卡密" :border="false" style="background-color: #F3F6FB; width: 80%; margin: 10px auto;"></van-field>
                <div class="pt-20 pb-29" @click="onDialogClose">
                    <van-button v-if="cardErrorNum < 5" round class="pt-10 pb-29" color="#F59A23" style="height: 42px; width:120px;" @click="jihuoFn">
                      立即激活
                    </van-button>
                    <div style="color: #999"  v-else>
                      {{ countdown }}S后重新激活
                    </div>
                </div>
            </div>
        </van-dialog>
  </div>
</template>

<style lang="less" scoped>
.page {
  background: url("@/assets/images/mi-bg.png") #F3F6FB no-repeat top center;
  background-size: contain;
  min-height: 100vh;
}
.auth-button {
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: cornflowerblue;
}
</style>
